package handlers

import (
	"article-hub/cache"
	"article-hub/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := models.UserRole{
		Uid: uid,
		Rid: rid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "添加成功",
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "添加成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT * FROM
		roles
		left join user_roles ON user_roles.rid=roles.id
		WHERE
		user_roles.uid=1
	*/
	var role []models.Role
	models.DB.Table("roles").
		Joins("left join user_roles ON user_roles.rid=roles.id").
		Where("user_roles.uid=?", uid).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}
func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT * FROM
		nodes
		left join role_nodes ON role_nodes.nid=nodes.id
		WHERE
		role_nodes.rid=1
	*/
	var nodes []models.Node
	models.DB.Table("nodes").
		Joins("left join role_nodes ON role_nodes.nid=nodes.id").
		Where("role_nodes.rid=?", rid).
		Find(&nodes)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": nodes,
	})
}
func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var user []models.User
	redis_key := "user_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Debug().Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	var total int64
	models.DB.Table("users").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  user,
		"total": total,
	})
	return
}
func UserDetail(c *gin.Context) {
	uid := c.Query("uid")
	var user models.User

	redis_key := "user_detail_" + uid
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", uid).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return
}
